<?php

declare(strict_types=1);


namespace app\controller\mini;

use app\controller\admin\AdminBaseController;
use app\model\admin\Product;
use app\model\admin\ProductAttrResult;
use app\model\admin\ProductAttrValue;
use app\Request;
use app\model\admin\SysMember;
use app\model\mini\Cart;
use app\model\mini\MiniUser;
use app\model\mini\Order;
use app\model\mini\OrderLog;
use app\service\JwtAuth;
use think\facade\Db;

class PayController extends AdminBaseController
{
    public function payCallback(Request $request)
    {
        $params = $request->param();
        storage_log("支付回调参数:" . json_encode($params));
        storage_log('收到支付成功回调');
        $params = request()->param();
        $post_params = request()->post();
        // 请求类型


        //官方支付处理逻辑
        return $this->weixinCallback();
    }
    protected function weixinCallback()
    {


        // 获取到实例
        $pay_app = $this->payApp;
        $response = $pay_app->handlePaidNotify(function ($message, $fail) use ($pay_app) {
            $order_sn = $message['out_trade_no'];
            storage_log('handlePaidNotify-message' . json_encode($message));

            if ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                //充值业务类型订单
                $ret = $this->order($order_sn);
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            storage_log("处理支付回调ret" . json_encode($ret));
            if ($ret['result'] == true) {
                return true;
            } else {
                return $fail($ret['msg']);
            }
        });
        return $response->send();
    }
    public function order($order_sn)
    {

        $order_info = Order::with(['orderItem'])->where('order_sn', $order_sn)->where('pay_status', 0)->find();
        if (!$order_info) {
            storage_log('订单未找到或者已支付:' . $order_sn);
            return ['result' => true, 'msg' => '订单未找到或者已支付'];
        }

        storage_log('修改订单为已支付：' . $order_sn);

        // todo 计算佣金
        $res = Db::table('user_order')->where('id', $order_info->id)->update([
            "pay_status" => 1,
            "order_status" => 0, // 订单标记为待发货
            // "commission_money1" => $first_money,
            // "commission_money2" => $second_money,
            "updated_at" => time(),
            "pay_at" => time(),
            "act_remark" => "支付成功",
            "remark" => "支付成功",
        ]);
        if (!$res) {
            return ['result' => false, 'msg' => '更新订单支付状态失败'];
        }
        // todo支付成功模版消息

        // 记录订单日志
        OrderLog::create([
            "order_id" => $order_info->id,
            "message" => "订单支付完成"
        ]);
        return ['result' => true, 'msg' => '更改订单支付成功状态'];
    }
}
